package com.msb.mall.auth.controller;

import com.alibaba.fastjson.JSON;
import com.msb.common.constant.AuthConstant;
import com.msb.common.dto.MemberDTO;
import com.msb.common.dto.MemberLoginDTO;
import com.msb.common.utils.R;
import com.msb.mall.auth.feign.MemberFeignService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;

@RequestMapping("/login")
@Controller
public class LoginController {

    @Autowired
    private MemberFeignService memberFeignService;

    /**
     * 用户登录
     * @return
     */
    @PostMapping("/login")
    public String login(MemberLoginDTO dto, Model model, HttpSession session){
        R r = memberFeignService.login(dto);
        if (r.getCode()==0){
            // 密码正确，登录
            MemberDTO memberDTO = JSON.parseObject(JSON.toJSONString(r.get("memberEntity")), MemberDTO.class);
            session.setAttribute(AuthConstant.AUTH_SESSION_REDIS,memberDTO);
            System.out.println("-------------->>登录成功："+memberDTO);
            return "redirect:http://mall.msb.com/index";
        }else {
            // 密码错误
            model.addAttribute("error",r.getMessage());
            return "login";
        }

    }

    /**
     * 退出登录
     *
     * @param session
     * @return
     */
    @RequestMapping(value = "/logout")
    public String logout(HttpSession session) {
        session.removeAttribute("user");
        session.invalidate();
        return "redirect:http://auth.msb.com/login.html";
    }

}
